const router = require('koa-router')()
const query = require('../db/mysql')
router.prefix('/custom')


// 获取数据 分页
router.post('/getCustom', async (ctx, next) => {
    const { page, pagesize, name = '', status = '', star = '' } = ctx.request.body
    console.log(page, pagesize, name, status, star);
    const pageSize = (page - 1) * pagesize

    let sql = 'select * from custom where 1=1'
    let sql2 = 'select count(*) as total from custom where 1=1'
    if (name) {
        sql += ` and name like '%${name}%'`
        sql2 += ` and name like '%${name}%'`
    }
    if (status) {
        sql += ` and status='${status}'`
        sql2 += ` and status='${status}'`
    }
    if (star) {
        sql += ` and star='${star}'`
        sql2 += ` and star='${star}'`
    }
    let res = await query(sql += ` limit ${pageSize},${pagesize}`)
    let total = await query(sql2)
    ctx.body = {
        code: 200,
        msg: "成功",
        data: res,
        total: total[0].total
    }
})


// 删除一项
router.post('/delCustom', async (ctx) => {
    const { id } = ctx.request.body
    let res = await query(`delete from custom where id=${id}`)
    ctx.body = {
        code: 200,
        msg: "删除成功",
        data: res
    }
})

// 添加一项
router.post('/addCustom', async ctx => {
    const { name, status, star, firstname, phone } = ctx.request.body
    // 获取年、月、日
    var currentDate = new Date();
    let year = currentDate.getFullYear();
    let month = currentDate.getMonth() + 1;
    let days = currentDate.getDate();
    // 格式化日期字符串
    let endtime = year + '-' + (month < 10 ? '0' + month : month) + '-' + (days < 10 ? '0' + days : days);
    let day = 30
    console.log(name, status, star, firstname, phone, endtime, day);
    let res = await query(`insert into custom(name,status,star,firstname,phone,endtime,day) values('${name}','${status}','${star}','${firstname}','${phone}','${endtime}','${day}')`)
    ctx.body = {
        code: 200,
        msg: "添加成功",
        data: res
    }
})

router.post('/statusCustom', async ctx => {
    const { id, status } = ctx.request.body
    console.log(id, status);
    let res = await query(`update custom set status='${status}' where id=${id}`)
    ctx.body = {
        code: 200,
        msg: "更改成功",
        data: res
    }
})

router.post('/updCustom', async ctx => {
    const { name, status, star, firstname, phone, id } = ctx.request.body
    console.log(id, name, status, star, firstname, phone);
    let res = await query(`update custom set name='${name}',status='${status}',star='${star}',firstname='${firstname}',phone='${phone}' where id=${id}`)
    ctx.body = {
        code: 200,
        msg: "修改成功",
        data: res
    }
})

module.exports = router
